package com.ktvme.controller;


import com.ktvme.core.DolphinClient;
import com.ktvme.entity.Cluster;
import com.ktvme.process.ProcessDefineResp;
import com.ktvme.processInstance.ProcessInstanceCreateParam;
import com.ktvme.processInstance.ProcessInstanceQueryResp;
import com.ktvme.project.ProjectInfoResp;
import com.ktvme.result.PageResult;
import com.ktvme.result.Result;
import com.ktvme.service.ClusterService;
import com.ktvme.taskInstance.TaskInstanceQueryResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;

@RestController
@RequestMapping("/BDMobieOps/dophin")
@Slf4j
@Tag(name = " dolphin 接口")
public class DolphinController {

    @Autowired
    ClusterService clusterService;

    private DolphinClient getDolphinClient(String clusterId) {
        Cluster cluster = clusterService.getById(clusterId);
        if (cluster == null) {
            // 处理集群���找到的情况，例如抛出异常或返回默认值
            throw new IllegalArgumentException("Cluster not found with id: " + clusterId);
        }
        String url = cluster.getUrl();
        String token = cluster.getToken();
        return new DolphinClient(url, token);
    }

    @Operation(summary = "查询项目列表")
    @GetMapping("/{clusterId}/project/list")
    public Result<List<ProjectInfoResp>> projectList(@PathVariable("clusterId") String clusterId) {
        Cluster cluster = clusterService.getById(clusterId);
        String url = cluster.getUrl();
        String token = cluster.getToken();
        DolphinClient dophinClient = new DolphinClient(url, token);

        List<ProjectInfoResp> list = dophinClient.getProjectOperator().list();
        return Result.success(list);

    }
    @Operation(summary = "查询项目分页")
    @GetMapping("/{clusterId}/project/page")
    public Result<PageResult> projectPage(@PathVariable("clusterId")String clusterId,@PathParam("page") int page,@PathParam("size") int size) {
        Cluster cluster = clusterService.getById(clusterId);
        String url = cluster.getUrl();
        String token = cluster.getToken();
        DolphinClient dophinClient = new DolphinClient(url, token);
        log.info("查询集群:"+clusterId+",url:"+url+",token:"+token+",page:"+page+",size:"+size);
        PageResult<ProjectInfoResp> page1 = dophinClient.getProjectOperator().page(page, size);
        return Result.success(page1);
    }

    @Operation(summary = "查询工作流定义分页")
    @GetMapping("/{clusterId}/project/{projectCode}/process/page")
    public Result<PageResult> processPage
            (@PathVariable("clusterId")String clusterId,
             @PathVariable("projectCode") Long projectCode,
             int page,
             int size,
             String searchVal) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        PageResult<ProcessDefineResp> page1 = dolphinClient.getProcessOperator().page(projectCode, page, size, searchVal);
        return Result.success(page1);
    }

    @Operation(summary = "上线工作流定义")
    @GetMapping("/{clusterId}/project/{projectCode}/process/{processCode}/online")
    public Result onlineProcessDefinition(@PathVariable("clusterId")String clusterId,
                                          @PathVariable("projectCode") Long projectCode,
                                          @PathVariable("processCode") Long processCode) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean online = dolphinClient.getProcessOperator().onlineProcessDefinition(projectCode, processCode);
        if (online){
            return Result.success("上线成功");
        }
        else {
            return Result.error("上线失败");
        }
    }

    @Operation(summary = "下线工作流定义")
    @GetMapping("/{clusterId}/project/{projectCode}/process/{processCode}/offline")
    public Result offlineProcessDefinition(@PathVariable("clusterId")String clusterId,
                                           @PathVariable("projectCode") Long projectCode,
                                           @PathVariable("processCode") Long processCode) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean offline = dolphinClient.getProcessOperator().offlineProcessDefinition(projectCode, processCode);
       if (offline){ return Result.success("下线成功");}
        else { return Result.error("下线失败");}
    }

    @Operation(summary = "删除工作流定义")
    @DeleteMapping("/{clusterId}/project/{projectCode}/process/{processCode}")
    public Result deleteProcessDefinition(@PathVariable("clusterId")String clusterId,
                                           @PathVariable("projectCode") Long projectCode,
                                           @PathVariable("processCode") Long processCode) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean delete = dolphinClient.getProcessOperator().deleteProcessDefinition(projectCode, processCode);
        if (delete){ return Result.success("删除成功");}
        else { return Result.error("删除失败");}
    }

    @Operation(summary = "查询工作流实例分页")
    @GetMapping("/{clusterId}/project/{projectCode}/instance/page")
    public Result<PageResult> instancePage(@PathVariable("clusterId")String clusterId,
                                            @PathVariable("projectCode") Long projectCode,
                                            Integer page,
                                            Integer size,
                                           Long workflowCode) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        PageResult<ProcessInstanceQueryResp> page1 = dolphinClient.getProcessInstanceOperator().page(projectCode,workflowCode, page, size);
        return Result.success(page1);
    }

    @Operation(summary = "重新运行工作流实例")
    @GetMapping("/{clusterId}/project/{projectCode}/instance/{processInstanceId}/re_run")
    public Result reRunProcessInstance(@PathVariable("clusterId")String clusterId,
                                       @PathVariable("projectCode") Long projectCode,
                                       @PathVariable("processInstanceId") Long processInstanceId) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean reRun = dolphinClient.getProcessInstanceOperator().reRunProcessInstance(projectCode, processInstanceId);
        if (reRun)
            return Result.success("重新运行成功");
        else
            return Result.error("重新运行失败");
    }

    @Operation(summary = "暂停工作流实例")
    @GetMapping("/{clusterId}/project/{projectCode}/instance/{processInstanceId}/pause")
    public Result pauseProcessInstance(@PathVariable("clusterId")String clusterId,
                                       @PathVariable("projectCode") Long projectCode,
                                       @PathVariable("processInstanceId") Long processInstanceId) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean pause = dolphinClient.getProcessInstanceOperator().pauseProcessInstance(projectCode, processInstanceId);
        if (pause)
            return Result.success("暂停成功");
        else
            return Result.error("暂停失败");
    }

    @Operation(summary = "停止工作流实例")
    @GetMapping("/{clusterId}/project/{projectCode}/instance/{processInstanceId}/stop")
    public Result stopProcessInstance(@PathVariable("clusterId")String clusterId,
                                      @PathVariable("projectCode") Long projectCode,
                                      @PathVariable("processInstanceId") Long processInstanceId) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean stop = dolphinClient.getProcessInstanceOperator().stopProcessInstance(projectCode, processInstanceId);
        if (stop)
            return Result.success("停止成功");
        else
            return Result.error("停止失败");
    }

    @Operation(summary = "删除工作流实例")
    @DeleteMapping("/{clusterId}/project/{projectCode}/instance/{processInstanceId}")
    public Result deleteProcessInstance(@PathVariable("clusterId")String clusterId,
                                        @PathVariable("projectCode") Long projectCode,
                                        @PathVariable("processInstanceId") Long processInstanceId) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean delete = dolphinClient.getProcessInstanceOperator().deleteProcessInstance(projectCode, processInstanceId);
        if (delete)
            return Result.success("删除成功");
        else
            return Result.error("删除失败");
    }

    @Operation(summary = "开始工作流实���")
    @GetMapping("/{clusterId}/project/{projectCode}/instance/start")
    public Result startProcessInstance(@PathVariable("clusterId")String clusterId,
                                       @PathVariable("projectCode") Long projectCode,
                                       @RequestBody ProcessInstanceCreateParam processInstanceCreateParam) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        Boolean start = dolphinClient.getProcessInstanceOperator().startProcessInstance(projectCode, processInstanceCreateParam);
        if (start)
            return Result.success("开始成功");
        else
            return Result.error("开始失败");
    }

    @Operation(summary = "查询任务实例分页")
    @GetMapping("/{clusterId}/project/{projectCode}/task/page")
    public Result<PageResult> taskPage(@PathVariable("clusterId")String clusterId,
                                        @PathVariable("projectCode") Long projectCode,
                                        @PathParam("page") Integer page,
                                        Integer size,
                                        Long processInstanceId,
                                        String processInstanceName) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        PageResult<TaskInstanceQueryResp> page1 = dolphinClient.getTaskInstanceOperator().page(projectCode,page,size,processInstanceId,processInstanceName);
        return Result.success(page1);
    }

    @Operation(summary = "查询任务日志")
    @GetMapping("/{clusterId}/project/{projectCode}/task/{taskInstanceId}/log")
    public Result<String> taskLog(@PathVariable("clusterId")String clusterId,
                                  @PathVariable("projectCode") Long projectCode,
                                  @PathVariable("taskInstanceId") Long taskInstanceId,
                                  Integer skipLineNum,
                                  Integer limit
    ) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        String log = dolphinClient.getTaskInstanceOperator().queryLog(projectCode, skipLineNum, limit,taskInstanceId);
        return Result.success(log);
    }

    @Operation(summary = "查询任务日志最后几行")
    @GetMapping("/{clusterId}/project/{projectCode}/task/{taskInstanceId}/log/last")
    public Result<String> taskLogLast(@PathVariable("clusterId")String clusterId,
                                      @PathVariable("projectCode") Long projectCode,
                                      @PathVariable("taskInstanceId") Long taskInstanceId,
                                      Integer skipLineNum,
                                      Integer limit
    ) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        String log = dolphinClient.getTaskInstanceOperator().donwloadLog(projectCode, taskInstanceId);
        return Result.success(log);
    }

    @Operation(summary = "获取任务日志最后N行")
    @GetMapping("/{clusterId}/project/{projectCode}/task/{taskInstanceId}/log/tail")
    public Result<String> getTaskLogTail(
            @PathVariable("clusterId") String clusterId,
            @PathVariable("projectCode") Long projectCode,
            @PathVariable("taskInstanceId") Long taskInstanceId,
            @RequestParam(defaultValue = "100") Integer lastLineNum) {
        DolphinClient dolphinClient = getDolphinClient(clusterId);
        String log = dolphinClient.getTaskInstanceOperator().donwloadLog(projectCode, taskInstanceId, lastLineNum);
        return Result.success(log);
    }

}
